import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'

// https://vite.dev/config/
export default defineConfig({
    plugins: [
        vue(),
        vueDevTools(),
    ],
    resolve: {
        alias: {
            '@': fileURLToPath(new URL('./src', import.meta.url))
        },
    },
    server: {
        port: 5173,
        proxy: {
            '/api': {
                target: 'http://localhost:8080',
                changeOrigin: true,
                // 重写API路径，移除/api前缀，适配后端接口
                rewrite: (path) => path.replace(/^\/api/, ''),
                // 确保请求头被正确传递
                secure: false,
                preserveHeaderCase: true,
                configure: (proxy, options) => {
                    // 打印代理请求日志
                    proxy.on('proxyReq', (proxyReq, req, res) => {
                        console.log('代理请求:', req.method, req.url, '请求头:', proxyReq.getHeaders())
                    })
                    proxy.on('proxyRes', (proxyRes, req, res) => {
                        console.log('代理响应:', proxyRes.statusCode, req.url)
                        // 记录响应错误
                        if (proxyRes.statusCode >= 400) {
                            console.error('代理响应错误:', req.url, proxyRes.statusCode)
                            console.error('请求头:', req.headers)
                        }
                    })
                    // 处理错误
                    proxy.on('error', (err, req, res) => {
                        console.error('代理错误:', err, req.url)
                    })
                }
            }
        }
    }
})
